//
//  TLoginViewModel.m
//  Tikeyc
//
//  Created by ways on 16/8/26.
//  Copyright © 2016年 tikeyc. All rights reserved.
//

#import "TLoginViewModel.h"

#import "SPKitExample.h"
#import "SPUtil.h"

@implementation TLoginViewModel

- (instancetype)initLoginViewModel{
    self = [super init];
    
    if (self) {
        
        [self initialBind];
    }
    
    return self;
}

- (TUserInfoModel *)userInfoModel{
    if (!_userInfoModel) {
        _userInfoModel = [[TUserInfoModel alloc] init];
    }
    return _userInfoModel;
}

- (void)initialBind{
    
    TWeakSelf(self)
    self.loginButtonEnableSignal = [RACSignal combineLatest:@[RACObserve(self.userInfoModel,userName),RACObserve(self.userInfoModel, userPassword)] reduce:^id(NSString *userName,NSString *userPassword){
//        id value = @([[userName lowercaseString] isEqualToString:@"tikeyc"] && userPassword.length >= 6);
        id value = @(userPassword.length >= 6);
        weakself.loginButtonEnable = [value boolValue];
        return value;
    }];
    
    // 处理登录业务逻辑
    _requestCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        
        RACSignal *signal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            [params setValue:self.userInfoModel.userName forKey:@"mobile"];
            [params setValue:self.userInfoModel.userPassword forKey:@"password"];
//            [params setValue:self.signUpModel.verifiCode forKey:@"verifiCode"];
            
            NSMutableDictionary *authority = [NSMutableDictionary dictionary];
            [authority setValue:@"abcdefg" forKey:@"token"];
            NSMutableDictionary *paramsBig = [NSMutableDictionary dictionary];
            [paramsBig setValue:params forKey:@"params"];
            [paramsBig setValue:authority forKey:@"authority"];
            NSData *body = [NSJSONSerialization dataWithJSONObject:paramsBig options:NSJSONWritingPrettyPrinted error:nil];
            
            /*
             {"clientInfo":{"appVersion":"1.0","os":"ios"},"authority":{"token":"abcdefg"},
             "params":{"mobile":18588610197,"verifiCode":"1234","password":"abc123"}}
             */
            [TServiceTool POST:T_LOGIN body:body parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary  *_Nullable responseObject) {
                //                NSLog(@"responseObject:%@",responseObject);
                
                [SVProgressHUD dismissWithDelay:0.5];
                if ([responseObject isKindOfClass:[NSDictionary class]]) {
                    [self.userInfoModel mj_setKeyValues:responseObject];
                    if ([self.userInfoModel.msgCode intValue] == 100) {//登录成功
                        
                    } else {
                        [SVProgressHUD showErrorWithStatus:self.userInfoModel.message];
                    }
                } else {
                    [SVProgressHUD showErrorWithStatus:@"请求错误"];
                }
                [TUserManager defaultManager].userInfoModel = self.userInfoModel;
                [subscriber sendNext:responseObject];
                // 数据传送完毕，必须调用完成，否则命令永远处于执行状态
                [subscriber sendCompleted];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"error:%@",error.description);
                [subscriber sendNext:nil];
                [subscriber sendCompleted];
                [subscriber sendError:error];
                [SVProgressHUD showErrorWithStatus:@"服务器异常"];
            }];
            
            return nil;

            
        }];
        
        
        return signal;
    }];
    
    //监听登录产生的数据
    [_requestCommand.executionSignals.switchToLatest subscribeNext:^(id x) {
        
    }];
    
    // 监听登录状态
    @weakify(self)
    [[_requestCommand.executing skip:1] subscribeNext:^(id x) {
        @strongify(self)
        if ([x isEqualToNumber:@(YES)]) {
            
            NSLog(@"正在登录ing...");
            
        }else
        {
            NSLog(@"登录成功");
            //隐藏蒙版
            if ([self.userInfoModel.msgCode intValue] == 100) {//登录成功
                
                [[XGFMDBTool sharedFMDBManager] deleteObjById:TUSERINFO_TABLE_NAME_id fromTable:TUSERINFO_TABLE_NAME];
                [[XGFMDBTool sharedFMDBManager] insertDBwithId:TUSERINFO_TABLE_NAME_id type:nil position:@"0" WithObject:[self.userInfoModel mj_keyValues] fromTable:TUSERINFO_TABLE_NAME];
                
                
            }
            
        }
    }];
    
}


- (void)tryLoginOpenIMWithSuccessBlock:(void(^)())aSuccessBlock
                           failedBlock:(void (^)(NSError *))aFailedBlock
{
    __weak typeof(self) weakSelf = self;
    
//    [[SPUtil sharedInstance] setWaitingIndicatorShown:YES withKey:self.description];
    
    //这里先进行应用的登录
    
    //应用登陆成功后，登录IMSDK
    [[SPKitExample sharedInstance] callThisAfterISVAccountLoginSuccessWithYWLoginId:@"visitor888"
                                                                           passWord:@"taobao1234"
                                                                    preloginedBlock:^{
                                                                        [[SPUtil sharedInstance] setWaitingIndicatorShown:NO withKey:weakSelf.description];
                                                                        //                                                                        [weakSelf _pushMainControllerAnimated:YES];
                                                                    } successBlock:^{
                                                                        aSuccessBlock();
                                                                        //  到这里已经完成SDK接入并登录成功，你可以通过exampleMakeConversationListControllerWithSelectItemBlock获得会话列表
//                                                                        [[SPUtil sharedInstance] setWaitingIndicatorShown:NO withKey:weakSelf.description];
                                                                        
                                                                        //                                                                        [weakSelf _pushMainControllerAnimated:YES];
                                                                        
#if DEBUG
                                                                        // 自定义轨迹参数均为透传
                                                                        //                                                                        [YWExtensionServiceFromProtocol(IYWExtensionForCustomerService) updateExtraInfoWithExtraUI:@"透传内容" andExtraParam:@"透传内容"];
#endif
                                                                    } failedBlock:^(NSError *aError) {
                                                                        aFailedBlock(aError);
                                                                        [[SPUtil sharedInstance] setWaitingIndicatorShown:NO withKey:weakSelf.description];
                                                                        
                                                                        if (aError.code == YWLoginErrorCodePasswordError || aError.code == YWLoginErrorCodePasswordInvalid || aError.code == YWLoginErrorCodeUserNotExsit) {
                                                                            
                                                                            dispatch_async(dispatch_get_main_queue(), ^{
//                                                                                UIActionSheet *as = [[UIActionSheet alloc] initWithTitle:@"登录失败, 可以使用游客登录。\n（如在调试，请确认AppKey、帐号、密码是否正确。）" delegate:weakSelf cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"游客登录", nil];
//                                                                                [as showInView:weakSelf.view];
                                                                                [TAlertView showWithTitle:@"登录失败, 可以使用游客登录。\n（如在调试，请确认AppKey、帐号、密码是否正确。）" message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"游客登录"] type:UIAlertControllerStyleActionSheet andParentView:nil andAction:^(NSInteger buttonIndex) {
                                                                                    
                                                                                }];
                                                                            });
                                                                        }
                                                                        
                                                                    }];
}


@end












